﻿using SuperX.Common.Helper;
using SuperX.Common.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace SuperX.Helper
{
    public static class Helper
    {
        public static T DeepCopy<T>(this object value)
        {
            if (value == null) return default(T);
            return JsonHelper.JsonDeserialize<T>(JsonHelper.JsonSerialize(value));
        }

        public static long DateTimeToUnix(this DateTime value)
        {
            var unixTime = (long)(value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            return unixTime >= 0 ? unixTime : 0;
        }

        public static ILookup<string, IFuncion> MethodToLookup(this object obj)
        {
            try
            {
                List<IFuncion> methods = obj.GetType()
                    .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Select(
                    t => (IFuncion)new FuncionInfo
                    {
                        MethodName = t.Name,
                        ExecObj = obj,
                        Method = t,
                        Handler = DynamicEmitCalls.GetMethodInvoker(t)
                    }).ToList();
                return methods.ToLookup(t => t.MethodName);
            }
            catch (System.Exception ex)
            {
                Logger.Exception(ex);
                return null;
            }
        }
    }
}